package com.itheima;

import org.junit.Test;

public class Topic42 {

    public int trap(int[] height) {

        int a = 0;
        int b = a + 1;
        int maxV = 0;

        if(height.length == 0 || height.length == 1 || height.length == 2){
            return 0;
        }
        while(a < height.length){

            b = a + 1;
            while(b < height.length){
                if (height[b] >= height[a]){
                    int t = Math.min(height[a], height[b]);
                    for(int i = a + 1; i < b; i++) {
                        maxV = maxV + (t - height[i]);
                    }
                    a = b;
                    break;
                }

                b++;
            }
            if(b == height.length) {
                int cm = a + 1;
                if(cm >= height.length) {
                    break;
                }
                for(int i = a + 1; i < height.length; i++) {
                    if(i >= cm && height[i] > height[cm]){
                        cm = i;
                    }
                }
//                System.out.println(cm);
                int t = Math.min(height[a], height[cm]);
                for(int i = a + 1; i < cm; i++) {
                    maxV = maxV + (t - height[i]);
                }

                a++;
            }

        }
        System.out.println(maxV);
        return maxV;
    }

    public int trap1(int[] height) {


        int l = 0;
        int r = height.length - 1;
        int lm = height[l];
        int rm = height[r];
        int ans = 0;

        while(l < r){

            if(lm <= rm) {
                ans = ans + lm - height[l];

                l++;
                if(lm < height[l]) {
                    lm = height[l];
                }
            } else{
                ans = ans + rm - height[r];

                r--;
                if(rm < height[r]) {
                    rm = height[r];
                }
            }

        }
        System.out.println(ans);
        return ans;
    }

    @Test
    public void test() {
        trap1(new int[]{6,8,5,0,0,6,5});
    }
}
